<script setup>
import { ref, inject, onMounted } from "vue";
// 修改这一行，使用命名导入
import { MdEditor } from "md-editor-v3";
import "md-editor-v3/lib/style.css";
import { ElMessage } from "element-plus";
import { useUserStore } from "../stores/user";
import { serviceUrl } from "../utils/request";

const axios = inject("axios");

const userStore = useUserStore();

const formData = ref({
  authorId: 0,
  tagId: 0,
  title: "",
  describe: "",
  tag: "",
  content: "",
  type: 1,
});

onMounted(() => {
  fetchTagList();
  userStore.initUserFromStorage();
  console.log(userStore.userInfo?.record.userId);
  formData.value.authorId = userStore.userInfo?.record.userId;
});

const fetchTagList = async () => {
  const res = await axios.get("/tagList");
  tagList.value = res.data.data.record;
};

const tagList = ref([]);

const publishArticle = async () => {
  try {
    console.log(formData.value);
    const res = await axios.post("/user/article", {
      ...formData.value,
    });
    if (res.data.code === 200) {
      ElMessage.success("发布成功");
    } else {
      ElMessage.error("发布失败");
    }
  } catch {
    ElMessage.error("发布失败");
  }
};

// md上传图片
const onUploadImg = async (files, callback) => {
  const res = await Promise.all(
    files.map((file) => {
      return new Promise((success, fail) => {
        const form = new FormData();
        form.append("file", file);

        axios
          .post("/common/file/upload", form, {
            headers: {
              "Content-Type": "multipart/form-data",
            },
          })
          .then((res) => success(res.data.data))
          .catch((error) => fail(error));
      });
    })
  );

  // 遍历结果数组
  callback(
    res.map((item) => serviceUrl + item.filePath)
  );
};

const handleChangeTags = (tagSelect) => {
  console.log("选择了", tagSelect);
  formData.value.tagId = tagSelect;
  console.log(formData.tagId);
};

// md编辑器工具栏
// 通过'-'分割两个工具，通过'='实现左右放置
const toolbars = [
  "bold",
  "underline",
  "italic",
  "-",
  "title",
  "strikeThrough",
  "sub",
  "sup",
  "quote",
  "unorderedList",
  "orderedList",
  "task",
  "-",
  "codeRow",
  "code",
  "link",
  "image",
  "table",
  "mermaid",
  "katex",
  "-",
  "revoke",
  "next", // 'save',
  "=",
  "pageFullscreen",
  "fullscreen",
  "preview",
  "previewOnly",
  "htmlPreview",
  "catalog",
  "github",
];
</script>

<template>
  <h1>发布文章</h1>

  <el-form
    ref="formRef"
    :model="formData"
    label-position="top"
    class="publish-page"
  >
    <!-- <el-form-item label="文章标题">
        <el-input v-model="formData.title" placeholder="请输入标签名" />
      </el-form-item>
      <el-form-item label="文章简介">
        <el-input v-model="formData.describe" placeholder="请输入文章简介" />
      </el-form-item> -->
    <el-form-item label="文章标题" class="form-group">
      <el-input
        type="text"
        id="title"
        v-model="formData.title"
        placeholder="请输入文章标题"
        size="large"
        clearable
      />
    </el-form-item>
    <el-form-item label="文章简介" class="form-group">
      <el-input
        type="textarea"
        v-model="formData.describe"
        :rows="3"
        placeholder="请输入文章简介"
      />
    </el-form-item>

    <el-form-item label="文章内容" class="form-group">
      <MdEditor
        v-model="formData.content"
        placeholder="请输入Markdown格式的文章内容"
        :toolbarsExclude="['github', 'save']"
        :toolbars="toolbars"
        inputBoxWidth="45%"
        insertLinkDirect
        codeTheme="atom"
        autoDetectCode
        @onUploadImg="onUploadImg"
      />
    </el-form-item>

    <el-form-item label="所属标签" class="form-group">
      <el-select
        v-model="formData.tag"
        size="large"
        @change="handleChangeTags"
        placeholder="请选择标签"
      >
        <el-option
          v-for="item in tagList"
          :key="item.tagId"
          :label="item.tagName"
          :value="item.tagId"
        />
      </el-select>
    </el-form-item>

    <button class="publish-btn" @click="publishArticle">发布文章</button>
  </el-form>
</template>

<style scoped>
.publish-page {
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 30px;
}

h1 {
  text-align: center;
  color: #333;
}

.form-group {
  margin-bottom: 20px;
}

label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #333;
}

input,
textarea {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 1rem;
  transition: border-color 0.3s;
}

input:focus,
textarea:focus {
  border-color: #646cff;
  outline: none;
}

.publish-btn {
  background-color: #646cff;
  color: white;
  border: none;
  padding: 12px 20px;
  border-radius: 4px;
  font-size: 1rem;
  cursor: pointer;
  transition: background-color 0.3s;
  display: block;
  width: 100%;
  margin-top: 20px;
}

.publish-btn:hover {
  background-color: #535bf2;
}

:deep(.md-editor-footer) {
  align-items: center;
}

/* 调整编辑器高度 */
/* :deep(.md-editor) {
  height: 500px;
} */
</style>
